__author__ = "Feng Gu"
__email__ = "contact@fenggu.me"

"""
   isort:skip_file
"""

import ast
import os
import re

LAYOUT = "env"

pattern = re.compile(r"(?<!^)(?=[A-Z])")

env_path = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
    "magent2",
    "environments",
)

subfolders = next(os.walk(env_path))[1]
subfolder_dirs = list(map(lambda x: os.path.join(env_path, x), subfolders))
for dir in subfolder_dirs:
    # there should be only 1 file in each folder besides __init__.py
    files = list(filter(lambda x: not x.startswith("__init__"), os.listdir(dir)))
    file = os.path.join(dir, files[0])
    file_name = files[0].split(".")[0]

    # getting docstring
    file_contents = ""
    with open(file) as fd:
        file_contents = fd.read()
    module = ast.parse(file_contents)
    docstring = ast.get_docstring(module)
    if docstring is None:
        docstring = ""

    # output path
    output_path = os.path.join(
        os.path.dirname(os.path.dirname(__file__)),
        "environments",
        f"{file_name}.md",
    )

    front_matter = f"""---
autogenerated:
title: {file_name}
---
"""
    title = f"# {file_name}"

    if docstring is None or docstring == "":
        docstring = "No information provided"
    all_text = f"""{front_matter}

{docstring}
"""
    file = open(output_path, "w+", encoding="utf-8")
    file.write(all_text)
    file.close()
